var ns, printModel;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            totalcount: 0,
            keywords: '',
            pageindex: 1,
            pagesize: 20,
            totalPage: 1,
            current_item_length: 0,
            is_searching: false,
            scroll_top: 0,
            can_scroll: false,
            source: 'choosezc',
            exceptids: '',
            disablechoosestatus: false,
            disablechoosesrepairetatus: false
        },
        searchform: {
            TypeName: '',
            TypeID: '',
            Status: '',
            DeptName: '',
            BranchCode: '',
            UserGW: '',
            DepartmentID: 0,
            UserRealName: '',
            UserName: '',
            LocTitle: '',
            LocationID: '',
            RepairStatus: -1,
            IsPublic: 0,
            printStatus: 0
        },
        list: [],
        printList: [],
        canprintzc: false,
        isSelectAll: false
    },
    methods: {
        get_data: function () {
            var that = this;
            var shared = '';
            if (that.searchform.IsPublic == 1) {
                shared = 0;
            } else if (that.searchform.IsPublic == 2) {
                shared = 1;
            }
            ns.post({
                action: 'APP_GETZCLIST',
                p: that.form.pageindex,
                pagecount: that.form.pagesize,
                searchstr: that.form.keywords,
                status: that.searchform.Status,
                except: that.form.exceptids,
                typeid: that.searchform.TypeID,
                branchcode: that.searchform.BranchCode,
                usergw: that.searchform.DepartmentID,
                uname: that.searchform.UserName,
                locationid: that.searchform.LocationID,
                repairstatus: that.searchform.RepairStatus,
                shared: shared,
                printStatus: that.searchform.printStatus
            }, function (succeed, data, err) {
                if (succeed) {
                    that.list = data.list;
                    that.form.totalcount = data.total;
                    if (that.list.length < that.form.totalcount) {
                        that.form.can_scroll = true;
                    }
                    that.form.totalPage = Math.floor(that.form.totalcount / that.form.pagesize)
                    if (that.form.totalcount % that.form.pagesize > 0) {
                        that.form.totalPage += 1;
                    }
                    that.isSelectAll = false;
                } else if (err) {
                    ns.toast(err);
                }
            }, {
                toast: true
            });
        },
        do_search: function () {
            var that = this;
            var name = 'printzcsearchbar_frm';
            var url = 'printzcsearchbar_frm.html';
            var x = 0;
            var y = ns.getPageParam('header_h') || 25;
            var w = api.winWidth;
            var h = api.winHeight - y;
            ns.openFrame(name, url, {
                type: 'movein',
                subType: 'from_right',
                x: x,
                y: y,
                h: h,
                w: w
            }, {
                keywords: that.form.keywords,
                source: that.form.source,
                TypeName: that.searchform.TypeName,
                TypeID: that.searchform.TypeID,
                Status: that.searchform.Status,
                RepairStatus: that.searchform.RepairStatus,
                DeptName: that.searchform.DeptName,
                BranchCode: that.searchform.BranchCode,
                UserGW: that.searchform.UserGW,
                DepartmentID: that.searchform.DepartmentID,
                DepartmentName: that.searchform.DepartmentName,
                UserRealName: that.searchform.UserRealName,
                UserName: that.searchform.UserName,
                LocTitle: that.searchform.LocTitle,
                LocationID: that.searchform.LocationID,
                IsPublic: that.searchform.IsPublic,
                disablechoosestatus: that.form.disablechoosestatus,
                disablechoosesrepairetatus: that.form.disablechoosesrepairetatus,
                printStatus: that.searchform.printStatus
            });
        },
        goPre() {
            var that = this;
            if (that.form.pageindex > 1) {
                that.form.pageindex -= 1;
            }
            that.get_data();
        },
        goNext() {
            var that = this;
            if (that.form.pageindex < that.form.totalPage) {
                that.form.pageindex += 1;
            }
            that.get_data();
        },
        do_select_all: function () {
            var that = this;
            that.isSelectAll = !that.isSelectAll;
            for (var i = 0; i < that.list.length; i++) {
                var item = that.list[i];
                item.ischecked = that.isSelectAll;
            }
        },
        do_select_zcitem: function (item) {
            var that = this;
            item.ischecked = !item.ischecked;
        },
        do_save: function () {
            var that = this;
            var idlist = [];
            for (var i = 0; i < that.list.length; i++) {
                var item = that.list[i];
                if (item.ischecked) {
                    idlist.push(item.ID);
                }
            }
            if (idlist.length == 0) {
                ns.toast('请选择资产');
                return;
            }
            api.sendEvent({
                name: 'do_choose_zc_complete',
                extra: {
                    ids: JSON.stringify(idlist)
                }
            });
            setTimeout(function () {
                api.closeWin();
            }, 500);
        },
        pull_refresh_init: function () {
            var that = this;
            var pullRefresh = new auiPullToRefresh({
                container: document.querySelector('.aui-refresh-content'),
                triggerDistance: 100
            }, function (ret) {
                if (ret.status == "success") {
                    setTimeout(function () {
                        that.form.pageindex = 1;
                        that.get_data();
                        pullRefresh.cancelLoading(); //刷新成功后调用此方法隐藏
                    }, 1500)
                }
            })
            var scroll = new auiScroll({
                listen: true,
                distance: 5 //判断到达底部的距离，isToBottom为true
            }, function (ret) {
                if (ret.isToBottom && that.form.can_scroll) {
                    if (that.form.scroll_top > ret.scrollTop) {
                        that.form.scroll_top = ret.scrollTop;
                        return;
                    }
                    that.form.scroll_top = ret.scrollTop + 1;
                    that.form.pageindex++;
                    that.get_data();
                }
            });
        },
        do_search_keywords: function () {
            var that = this;
            var title = '搜索';
            var name = 'zcsearch_frm';
            ns.openWin(name, title, {
                source: that.form.source
            });
        },
        convertcss: function (status) {
            switch (status) {
                case 10:
                    return "free";
                    break;
                case 15:
                    return "receive";
                    break;
                case 20:
                    return "using";
                    break;
                case 30:
                    return "lend";
                    break;
                case 100:
                    return "pendispose";
                    break;
                case 200:
                    return "dispose";
                    break;
            }
            return "dispose";
        },
        do_connect_print: function () {
            var that = this;
            that.printList = [];
            for (var i = 0; i < that.list.length; i++) {
                var item = that.list[i];
                if (item.ischecked) {
                    that.printList.push(item);
                }
            }
            if (that.printList.length == 0) {
                ns.toast('请选择资产');
                return;
            }
            ns.confirm({
                msg: '确认打印当前选中的(' + that.printList.length + ')个资产?'
            }, function () {
                var ret = printModel.getConnectState();
                if (ret.status && ret.state[0]) {
                    setTimeout(() => {
                        that.do_print(0);
                    }, 1000);
                    return;
                }
                var lastDevice = api.getPrefs({
                    sync: true,
                    key: 'last_print_device'
                });
                if (lastDevice) {
                    printModel.connectBleByMacAddress({
                        macAddress: lastDevice
                    }, function (ret, err) {
                        if (ret.status) {
                            if (ret.message == '已连接') {
                                that.connect_id = lastDevice;
                                setTimeout(() => {
                                    that.do_print(0);
                                }, 1000);
                            }
                            else if (ret.message == '连接失败') {
                                that.open_deivce();
                            }
                            else {
                                api.toast({
                                    msg: '打印机连接中'
                                })
                            }
                        }
                    });
                } else {
                    that.open_deivce();
                }
            })
        },
        open_deivce() {
            var that = this;
            printModel.connectBle(function (ret, err) {
                if (ret.status) {
                    if (ret.message == '已连接') {
                        if (ret.data && ret.data.macAddress) {
                            that.connect_id = ret.data.macAddress;
                            api.setPrefs({
                                key: 'last_print_device',
                                value: that.connect_id
                            });
                            setTimeout(() => {
                                that.do_print(0);
                            }, 1000);
                        } else {
                            api.toast({
                                msg: '打印机连接失败'
                            })
                        }
                    }
                    else if (ret.message == '连接失败') {
                        api.toast({
                            msg: '打印机连接失败'
                        })
                    }
                    else {
                        api.toast({
                            msg: '打印机连接中'
                        })
                    }
                }
            });
        },
        do_print(index) {
            var that = this;
            if (index >= that.printList.length) {
                var IdList = [];
                that.printList.forEach(function (item) {
                    IdList.push(item.ID);
                })
                var options = {
                    action: 'APP_PRINTZC',
                    Ids: JSON.stringify(IdList)
                }
                ns.post(options, function (succeed, data, err) {
                    if (succeed) {
                        ns.toast('打印完成');
                        that.goNext();
                        that.printList = [];
                    } else if (err) {
                        ns.toast(err);
                    }
                }, {
                    toast: true
                });
                return;
            }
            var printItem = that.printList[index];
            var rows = [{
                lineType: 'size',
                width: 80,
                height: 50
            }, {
                lineType: 'gap',
                data: 1
            }, {
                lineType: 'cls'
            }]
            var nameArray = that.spliceStr(printItem.Name);
            var codeArray = that.spliceStr(printItem.Title);
            // var nameArray = that.spliceStr('笔记本电脑真好用xxx（型号1对对对-12323）aa打广告过过多多');
            // var codeArray = that.spliceStr('rtyywwww-332233232aasdd好啊啊');
            var top = (6 - nameArray.length - codeArray.length) * 20;
            for (let i = 0; i < nameArray.length; i++) {
                var title = (i == 0 ? '资产名称:' : '') + nameArray[i];
                var myTop = top + (i * 40);
                rows.push({//绘制文本
                    lineType: 'text',
                    x: 20,
                    y: myTop,
                    rotation: 0,
                    xscal: 1,
                    yscal: 1,
                    data: title
                })
            }
            top += nameArray.length * 40 + 20;
            for (let i = 0; i < codeArray.length; i++) {
                var title = (i == 0 ? '资产分类:' : '') + codeArray[i];
                var myTop = top + (i * 40);
                rows.push({//绘制文本
                    lineType: 'text',
                    x: 20,
                    y: myTop,
                    rotation: 0,
                    xscal: 1,
                    yscal: 1,
                    data: title
                })
            }
            top += codeArray.length * 40 + 20;
            rows.push({//绘制code128
                lineType: 'code128',
                x: 20,
                y: top,
                height: 48,
                rotation: 0,
                data: printItem.Code
            })
            rows.push({//绘制qrcode
                lineType: 'qrcode',
                x: 370,
                y: 60,
                level: 'L',
                cellwith: 6,
                rotation: 0,
                data: CONFIG.url + '/wx/bgxt/zc_detail.html?id=' + printItem.ID
            })
            printModel.printLabel({
                rows: rows
            }, function (ret, err) {
                that.do_print(index + 1);
            });
        },
        spliceStr(str) {
            var textArray = [];
            if (!str) {
                return textArray;
            }
            var len = 0;
            var text = '';
            for (let i = 0; i < str.length; i++) {
                var index = escape(str[i]).indexOf("%u");
                if (index < 0) {
                    len += 1;
                } else {
                    len += 2;
                }
                text += str[i];
                var total = index > 0 ? 19 : 20;
                if (len >= total && i < str.length - 1 && textArray.length == 0) {
                    textArray.push(text);
                    text = '';
                    len = 0;
                    continue;
                }
                if (i == str.length - 1) {
                    if (text.length > total) {
                        text = text.substring(0, 17) + '...';
                    }
                    textArray.push(text);
                }
            }

            return textArray;
        }
    }
});
apiready = function () {
    api.parseTapmode();
    printModel = api.require('xGprinterPlus');
    ns = window.Foresight.Util;
    app.form.keywords = ns.getPageParam('keywords') || '';
    app.searchform.Status = ns.getPageParam('status') || 0;
    app.canprintzc = ns.getPageParam('canprintzc') || '';
    app.searchform.RepairStatus = api.pageParam.repairstatus;
    if (app.searchform.RepairStatus < 0 || app.searchform.RepairStatus == null || app.searchform.RepairStatus == undefined) {
        app.searchform.RepairStatus = -1;
    }
    app.form.exceptids = ns.getPageParam('exceptids') || ''
    app.form.disablechoosestatus = ns.getPageParam('disablechoosestatus') || false;
    app.form.disablechoosesrepairetatus = ns.getPageParam('disablechoosesrepairetatus') || false;
    //app.pull_refresh_init();
    setTimeout(function () {
        app.get_data();
    }, 500);
    api.addEventListener({
        name: 'do_save_choosezc'
    }, function () {
        app.do_save();
    });
    api.addEventListener({
        name: 'do_print_choosezc'
    }, function () {
        app.do_connect_print();
    });
    api.addEventListener({
        name: 'do_open_searchchoosezc'
    }, function () {
        app.do_search_keywords();
    });
    api.addEventListener({
        name: 'do_search_complete'
    }, function (ret) {
        if (ret.value.source == app.form.source) {
            if (ret.value && ret.value.keywords) {
                app.form.keywords = ret.value.keywords;
                app.form.pageindex = 1;
                app.get_data();
            }
        }
    });
    api.addEventListener({
        name: 'do_print_searchbar_complete'
    }, function (ret) {
        if (ret.value.source == app.form.source) {
            if (ret.value) {
                app.form.keywords = ret.value.keywords;
                app.searchform.TypeID = ret.value.TypeID;
                app.searchform.TypeName = ret.value.TypeName;
                app.searchform.Status = ret.value.Status;
                app.searchform.RepairStatus = ret.value.RepairStatus;
                app.searchform.DeptName = ret.value.DeptName;
                app.searchform.BranchCode = ret.value.BranchCode;
                app.searchform.UserGW = ret.value.UserGW;
                app.searchform.DepartmentID = ret.value.DepartmentID;
                app.searchform.UserRealName = ret.value.UserRealName;
                app.searchform.UserName = ret.value.UserName;
                app.searchform.LocTitle = ret.value.LocTitle;
                app.searchform.LocationID = ret.value.LocationID;
                app.searchform.IsPublic = ret.value.IsPublic;
                app.searchform.printStatus = ret.value.printStatus;
            }
            app.form.pageindex = 1;
            app.get_data();
        }
    });
}
